package com.nmgydy.util;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class AccessTokenUtil {

	private static String accessTokenKey = "wx_access_token";
	private static String appid = ConfigUtil.getValue("weixin.appid");
	private static String secret = ConfigUtil.getValue("weixin.appsecret");

	public static String getAccessToken(){
		String accessToken = (String) CacheUtil.get(accessTokenKey);
		if(accessToken == null){
			System.out.println("requestAccessToken");
			accessToken = requestAccessToken();
		}
		return accessToken;
	}

	private static synchronized String requestAccessToken(){
		String url = "https://api.weixin.qq.com/cgi-bin/token";
		Map<String,String> params = new HashMap<String, String>();
		params.put("grant_type", "client_credential");
		params.put("appid", appid);
		params.put("secret", secret);
		try {
			HttpClientResponse res = HttpsClient.get(url,params);
			JSONObject obj = res.asJSONObject();
			if(obj != null){
				String accessToken = obj.getString("access_token");
				int expireTime = obj.getIntValue("expires_in");
				CacheUtil.put(accessTokenKey, accessToken, expireTime);
				return accessToken;
			}else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		System.out.println(getAccessToken());
		System.out.println(getAccessToken());
	}
}
